package com.briup.day20;

public class Test_Message {
    public static void main(String[] args) {
        Plate plate = new Plate();
        Thread t1=new Producer("厨师1",plate);
        Thread t2=new Consumer("吃货1",plate);
        t1.start();
        t2.start();
    }
}
//定义公共资源 盘子类
class Plate{
    //包子默认为0
    int num=0;

}
//生产者线程 生产包子 消费者线程 消费包子
class Producer extends Thread {
    private Plate plate;

    public Producer(String name, Plate plate) {
        super(name);
        this.plate = plate;
    }

    public void run() {
        for (int i = 1; i < 100; i++) {
        synchronized (plate) {
            //如果包子数量大于0 ，不生产，进入waiting状态
                if (plate.num > 0) {
                    try {
                        plate.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("第" + i + "次" + this.getName() + "生产包子");
                plate.num++;
                System.out.println("生产完成，包子数量" + plate.num+"快来吃包子");
                //通知消费者线程操作num
                plate.notify();
            }
        }
    }
}
class Consumer extends Thread {
    private Plate plate;

    public Consumer(String name, Plate plate) {
        super(name);
        this.plate = plate;
    }
    public void run() {
        for (int i = 1; i < 100; i++) {
            synchronized (plate) {
                if (plate.num == 0) {
                    try {
                        plate.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("第" + i + "次" + this.getName() + "吃包子");
                plate.num++;
                System.out.println("吃完包子，包子数量" + plate.num+"快来生产包子");
                //通知消费者线程操作num
                plate.notify();
            }
        }
    }
}